<?php

namespace StudyBuddy;

use StudyBuddy\OFacebook;

/**
 * Static class that holds html vsprintf-based
 * templates for generating login form
 * and its components
 */
class LoginForm {

    protected static function forMember(Registry $oRegistry) {
        if (empty($_SESSION['welcome'])) {
            $Translator = $oRegistry->Tr;

            $oViewer = $oRegistry->Viewer;
            $invite = self::makeInviteLink($oViewer);
            $url = $oViewer->getProfileUrl();
            $avatar = $oViewer->getAvatarImgSrc();
            $displayName = $oViewer->getDisplayName();

            // facebook-php-3.1.1
            $aFacebookConf = $oRegistry->Ini->getSection('FACEBOOK');
            $oFacebook = new OFacebook(array(
                        'appId' => $aFacebookConf['APP_ID'],
                        'secret' => $aFacebookConf['APP_SECRET']
                    ));
            $user = $oFacebook->getUser();
            if ($user) {
                $a = array(
                    $avatar,
                    $displayName,
                    $Translator['Logout'],
                    $invite,
                    'settings' => "Controls",
                    'url' => $url,
//                    'a_logout' => '#',
                    'a_logout' => '/logout/',
//                    'ajax' => 'ajax'
                    'ajax' => ''
                );
            } else {
                $a = array(
                    $avatar,
                    $displayName,
                    $Translator['Logout'],
                    $invite,
                    'settings' => "Controls",
                    'url' => $url,
                    'a_logout' => '/logout/',
                    'ajax' => ''
                );
            }

            d('cp aVals: ' . print_r($a, 1));
            $_SESSION['welcome'] = \tplWelcome::parse($a, false);
            d('SESSION[welcome]: ' . $_SESSION['welcome']);
        } else {
            d('Welcome menu already existed! : ' . $_SESSION['welcome']);
        }

        return $_SESSION['welcome'];
    }

    /**
     * Make contents of login or welcome
     * block, depending on status of user
     *
     * @param Registry $oRegistry
     *
     * @return html of the Welcome or Login Block
     * that will be shown on top of page (in header)
     */
    public static function makeWelcomeMenu(Registry $oRegistry) {

        if ($oRegistry->Viewer->isGuest()) {
            d('going to make login form');

            return self::forGuest($oRegistry);
        } else {
            return self::forMember($oRegistry);
        }
    }

    /**
     * Make html for guest user
     * it will consist of login form
     * and another div with welcome guest message
     * and signup buttons
     *
     *
     * @param Registry $oRegistry
     *
     * @return string html
     */
    protected static function forGuest(Registry $oRegistry) {

        d('SESSION: ' . print_r($_SESSION, 1));

        if (empty($_SESSION['guest_block']) || !empty($_SESSION['login_error'])) {

            $html = '';

            $html = self::makeLoginBlock($oRegistry) . self::makeWelcomeGuest($oRegistry);
            /**
             * If !empty($_SESSION['login_error']) is set
             * then don't store the login form in session
             * and just return it.
             * Otherwise the form with the login error
             * message will be cached and will be passed from
             * page to page even if user not trying to login again
             *
             * In this case we unset login error from session
             * so it will not be reused on next page
             * and just return login form, so login
             * form is not caches in session and login error
             * is only show this one time!
             */
            if (!empty($_SESSION['login_error'])) {
                unset($_SESSION['login_error']);

                return $html;
            }

            $_SESSION['guest_block'] = $html;
        }

        return $_SESSION['guest_block'];
    }

    /**
     *
     * Generates login form and stores it in SESSION for caching
     * if login form already exists in SESSION then use it and skip
     * creation of html part
     *
     * @param Registry $oRegistry
     *
     * @return string html fragment containing div with login Form
     * and buttons for external login providers like facebook
     */
    protected static function makeWelcomeGuest(Registry $oRegistry) {

        if (empty($_SESSION['welcome_guest'])) {
            $Translator = $oRegistry->Tr;

            $socialBtns = self::makeSocialButtons($oRegistry);

            if (!empty($socialBtns)) {
                $socialBtns = '<div class="fl" id="socialbtns"><span>' . $Translator['Or Join with'] . ' </span>' . $socialBtns . '</div>';
            }

            $html = \tplWelcomeGuest::parse(array($Translator['Welcome!'], $Translator['Sign up'], $socialBtns), false);

            $_SESSION['welcome_guest'] = $html;
        }

        return $_SESSION['welcome_guest'];
    }

    /**
     * Make html with buttons of external signup
     * providers
     *
     *
     * @param Registry $oRegistry
     *
     * @return string html
     */
    public static function makeSocialButtons(Registry $oRegistry) {
        if (empty($_SESSION['social_buttons'])) {
            $oIni = $oRegistry->Ini;
            $html = '';
            $socialBtns = '';
            $gfcButton = $twitterButton = $fbButton = '';

            /**
             * Facebook
             */
            if (extension_loaded('curl') && isset($oIni->FACEBOOK)) {
                $aFB = $oIni['FACEBOOK'];

                if (!empty($aFB['APP_ID'])) {
                    //id="fbsignup"
                    d('$aFB: ' . print_r($aFB, 1));
                    $socialBtns .= '<img class="ajax fbsignup hand ttt" src=' . STUDYBUDDY_IMAGE_SITE . '"/images/f_32.png" width="32" height="32" alt="F" title="Sign in with your Facebook account">';
//                    $oFacebook = new OFacebook(array(
//                                'appId' => $aFB['APP_ID'],
//                                'secret' => $aFB['APP_SECRET']
//                            ));
//                    $loginUrl = $oFacebook->getLoginUrl();
//                    $socialBtns .= '<a href="'.$loginUrl.'" title=""><img class="hand ttt" src=' . STUDYBUDDY_IMAGE_SITE . '"/images/f_32.png" width="32" height="32" alt="F" title="Sign in with your Facebook account"></a>';
                }
            }

            /**
             * Twitter
             */
            if (extension_loaded('oauth') && isset($oIni->TWITTER)) {
                $aTW = $oIni['TWITTER'];
                if (!empty($aTW['TWITTER_OAUTH_KEY']) && !empty($aTW['TWITTER_OAUTH_SECRET'])) {
                    d('$aTW: ' . print_r($aTW, 1));
                    $socialBtns .= '<img class="ajax twsignin hand ttt" src=' . STUDYBUDDY_IMAGE_SITE . '"/images/t_32.png" width="32" height="32" alt="T" title="Sign in with Twitter Account">';
                }
            }


            /**
             * LinkedIn
             */
            if (extension_loaded('oauth') && isset($oIni->LINKEDIN)) {
                $aLI = $oIni['LINKEDIN'];
                if (!empty($aLI['OAUTH_KEY']) && !empty($aLI['OAUTH_SECRET'])) {
                    d('$aLI: ' . print_r($aLI, 1));
                    $socialBtns .= '<img class="ajax add_linkedin hand ttt" src=' . STUDYBUDDY_IMAGE_SITE . '"/images/linkedin_32.png" width="32" height="32" alt="T" title="Sign in with LinkedIn Account">';
                }
            }

            /**
             * Google Friend Connect
             */
            $GfcSiteID = $oIni->GFC_ID;
            if (extension_loaded('curl') && !empty($GfcSiteID)) {
                d('cp ' . strlen($gfcButton));

                $socialBtns .= '<img class="ajax gfcsignin hand ttt" src=' . STUDYBUDDY_IMAGE_SITE . '"/images/google_32.png" width="32" height="32" alt="Google" title="Sign in with Google"><img class="ajax gfcsignin hand ttt" src=' . STUDYBUDDY_IMAGE_SITE . '"/images/openid_32.png" width="32" height="32" alt="Open ID" title="Sign in with OpenID"><img class="ajax gfcsignin hand ttt" src=' . STUDYBUDDY_IMAGE_SITE . '"/images/aim_32.png" width="32" height="32" alt="AIM" title="Sign in with AOL"><img class="ajax gfcsignin hand ttt" src=' . STUDYBUDDY_IMAGE_SITE . '"/images/yahoo_32.png" width="32" height="32" alt="Yahoo" title="Sign in with Yahoo">';
            }

            $_SESSION['social_buttons'] = $socialBtns;
        }

        return $_SESSION['social_buttons'];
    }

    /**
     * Make div with login form
     * If login_error exists in session
     * it will also add that error to the form
     *
     * @param Registry $oRegistry
     * @return string html
     */
    protected static function makeLoginBlock(Registry $oRegistry) {
        $Translator = $oRegistry->Tr;

        $error = (!empty($_SESSION['login_error'])) ? $_SESSION['login_error'] : '';
        d('$error: ' . $error);

        $aVals = array(
            $Translator['Username'],
            $Translator['Password'],
            $Translator['Remember me'],
            $Translator['Username required'],
            $Translator['Forgot password?'],
            $Translator['Log in'],
            $error
        );

        return \tplLoginform::parse($aVals, false);
    }

    static function makeSearchBox(Registry $oRegistry) {

        if ($oRegistry->Viewer->isGuest()) {
            $searchbox = "";
        } else {
            $searchbox = \tplSearchForm::parse(array('q' => '', 'search_label' => 'S'));
        }

        return $searchbox;
    }

    /**
     * Make extra links like 'Invite Friends' based
     * on what type of user is currently logged in
     *
     * @param User $oUser
     *
     * @return string HTML string for links
     */
    protected static function makeInviteLink(User $oUser) {
        switch (true) {
            case ($oUser instanceof UserGfc):
                d('cp');
                $ret = '<div class="gfclinks"><a href="#" id="gfcset" class="ajax">FriendConnect settings</a> | <a href="#" class="ajax" id="gfcinvite">Invite friends</a></div>';
                break;
            case ($oUser instanceof UserFacebook):
                d('cp');
                $ret = '<div class="gfclinks"><a href="#" class="ajax" id="fbinvite" title="I\'ve registered at this site, and think you will enjoy your stay here too! Please check it out!">Invite your facebook friends</a></div>';
                break;

            case ($oUser instanceof UserTwitter):
                d('cp');
                $ret = '<div class="gfclinks"><a href="#" class="ajax" id="twinvite" title="Hey everyone! Join me at this site (Use the *Sign in with Twitter* button) ">Invite your Twitter friends</a></div>';
                break;
            default:
                d('cp');
                $ret = '';
        }

        return $ret;
    }

}
